var apiCode = require('../utils/openApiCode.js');
/**
 * 判断价值高低显示对应弹窗
 */
const isShowTypePope = async (prizeList, that, types) => {
    //获取弹窗需要显示的数据和通过价值判断显示哪个弹窗
    let prizeListCopy = JSON.parse(JSON.stringify(prizeList));
    if (prizeListCopy.length > 0) {
        let list = [];
        //红包信息
        for (let item of prizeListCopy) {
            if (item.prizeTypeId == 1 && item.status != '1' && item.status != '3' && item.status != '9') {
                if(item.doublePrizeAmount){
                    that.data.redEnvelopes = item.doublePrizeAmount / 100;
                }else{
                    that.data.redEnvelopes = item.prizeAmount / 100;
                }
            }
            if (item.prizeShowAmount > 0) {
                list.push(item);
            }
        }
        let prizeListMax = [];
        for (let i of types) {
            for (let item of list) {
                if (i.indexOf(',') > -1) {
                    let s = i.split(',')
                    if (s[0] == item.prizeTypeId || s[1] == item.prizeTypeId) {
                        prizeListMax.push(item);
                    }
                } else {
                    if (i == item.prizeTypeId) {
                        prizeListMax.push(item);
                    }
                }
            }
            if (prizeListMax.length > 0) {
                prizeListMax = prizeListMax.sort((a, b) => {
                    return b.prizeShowAmount - a.prizeShowAmount;
                });
                break;
            }
        }
        let productType = wx.getStorageSync('productType');
        let xryflag = false;
        //排序实物奖》世界杯卷》优惠券》权益卡（同类型有多个奖品优先显示prizeShowAmount价值高的）
        if (prizeListMax.length > 0 && prizeListMax[0].prizeShowAmount > 0) {
            that.data.handPrizeId = prizeListMax[0].id;
            //判断需要显示的弹板
            if (prizeListMax[0].prizeTypeId == 6 || prizeListMax[0].prizeTypeId == 20) {
                //实物或奖上奖数据
                that.data.entityData = prizeListMax[0];
                //实物或奖上奖弹窗显示
                that.data.isShowEntityPopup = true;
            } else if (prizeListMax[0].prizeTypeId == 14) { //世界杯竞猜
                let e = {};
                e.currentTarget = {};
                e.currentTarget.dataset = {};
                e.currentTarget.dataset.item = prizeListMax[0];
                //卷弹窗显示
                that.getPickInfo(e);
            } else if (prizeListMax[0].prizeTypeId == 16 || prizeListMax[0].prizeTypeId == 17) {//兑换卷和买赠卷
                //卷类型id
                that.data.prizeTypeId = prizeListMax[0].prizeTypeId;
                //卷数据
                that.data.couponPrizeInfo = prizeListMax[0];
                //卷弹窗显示
                that.data.isShowCouponPopup = true;
            } else if (prizeListMax[0].prizeTypeId == 19) {//权益卡
                if (productType == 4) {
                    xryflag = true;
                }
                let entryMode = '';
                if (productType == 1) {
                    entryMode = 'strongFragrance';
                }
                that.selectComponent('#benefitCardPopup').setData({
                    show: true,
                    prizeData: prizeListMax[0],
                    isxyr: xryflag,
                    entryMode
                })
            }
            //是否显示小手
            for (let i = 0; i < prizeList.length; i++) {
                if (prizeList[i].prizeShowAmount != null && prizeList[i].prizeShowAmount != "") {
                    if (prizeList[i].id == that.data.handPrizeId) {
                        prizeList[i].handFlag = 3;
                    } else {
                        prizeList[i].handFlag = 1;
                    }
                }
            }
        }
        wx.setStorageSync('prizeList', prizeList)
        if ((that.data.isShowEntityPopup || xryflag) && productType == 4) { //判断是否是心悠然分支
            that.data.isShowPrizes = false;
        }
        that.setData({
            redEnvelopes: that.data.redEnvelopes,
            entityData: that.data.entityData,
            isShowEntityPopup: that.data.isShowEntityPopup,
            prizeTypeId: that.data.prizeTypeId,
            isShowPrizes: that.data.isShowPrizes,
            couponPrizeInfo: that.data.couponPrizeInfo,
            isShowCouponPopup: that.data.isShowCouponPopup,
        })
        if (that.data.isShowEntityPopup) {
            receivePrizeHand(that);
        }
    }
}
/**
 * 是否显示领取奖励上面的小手
 */
const receivePrizeHand = (that) => {
    if (!that.data.materialInfo.receiveName || !that.data.materialInfo.receivePhone || !that.data.materialInfo.receiveAddress) {
        that.setData({
            handFlag: false
        })
        return;
    }
    let userName = that.data.materialInfo.receiveName;
    let phone = that.data.materialInfo.receivePhone;
    let detailAddress = that.data.materialInfo.receiveAddress;
    if (userName.trim() == "") {
        that.setData({
            handFlag: false
        })
        return;
    }
    if (userName.length > 20) {
        that.setData({
            handFlag: false
        })
        return;
    }
    if (phone.trim() == "") {
        that.setData({
            handFlag: false
        })
        return;
    }

    let a = /^1\d{10}$/;
    if (!a.test(phone)) {
        that.setData({
            handFlag: false
        })
        return;
    }
    if (that.data.address == '请选择地区') {
        that.setData({
            handFlag: false
        })
        return;
    }
    if (detailAddress.trim() == "") {
        that.setData({
            handFlag: false
        })
        return;
    }
    if (detailAddress.length > 60) {
        that.setData({
            handFlag: false
        })
        return;
    }
    that.setData({
        handFlag: true
    })
}
/**
 * 获取实物弹窗输入框内容并赋值给materialInfo
 * 调用receivePrizeHand判断是否所有输入框内容不为空在“领取奖品”按钮显示小手
 */
const setMaterialInfoAndIsHand = (type, that, value) => {
    if (type == 1) {
        that.data.materialInfo.receiveName = value;
        that.setData({
            materialInfo: that.data.materialInfo
        })
    } else if (type == 2) {
        that.data.materialInfo.receivePhone = value;
        that.setData({
            materialInfo: that.data.materialInfo
        })
    } else {
        that.data.materialInfo.receiveAddress = value;
        that.setData({
            materialInfo: that.data.materialInfo
        })
    }
    receivePrizeHand(that);
}
/**
 * 点击领取,进行实物奖兑奖
 */
const revicePrize = (that, netWork, addressInfo) => {
    that.isLoading(true, "正在提交...");
    let index = 0;
    let popupparam = {};
    for (let i = 0; i < that.data.prizeList.length; i++) {
        if (that.data.prizeList[i].prizeOrderId == that.data.entityData.prizeOrderId) {
            index = i;
            popupparam = that.data.prizeList[i];
            break;
        }
    }
    //兑奖
    netWork.POST('receiveMatter', {
        data: {
            userId: wx.getStorageSync('userId'),
            prizeOrderId: popupparam.prizeOrderId,
            prizeId: popupparam.prizeId,
            positioningStyle: wx.getStorageSync('positioningStyle'),
            positioningType: wx.getStorageSync('positioningType'),
            latitude: wx.getStorageSync('latitude'),
            longitude: wx.getStorageSync('longitude'),
            speed: wx.getStorageSync('speed'),
            accuracy: wx.getStorageSync('accuracy'),
            receiveName: that.data.formValue.userName, //收货人
            receivePhone: that.data.formValue.phone, //收货电话
            receiveProvinceId: addressInfo.receiveProvinceId, //省
            receiveCityId: addressInfo.receiveCityId, //市
            receivceDistrictId: addressInfo.receivceDistrictId, //区
            receiveProvinceName: addressInfo.receiveProvinceName,
            receiveCityName: addressInfo.receiveCityName,
            receiveDistrictName: addressInfo.receiveDistrictName,
            receiveAddress: that.data.formValue.detailAddress, //地址
            source: 1, //兑奖来源，1-正常流程兑奖 2-中奖记录兑奖
        },
        success: function (res) {
            that.isLoading(false);
            if (res.data.retCode == undefined) {
                wx.redirectTo({
                    url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                })
            }
            if (res.data.retCode == "0000") {
                that.setData({
                    isShowEntityTips: true,
                    isShowEntityPopup: false
                })
                setTimeout(function () {
                    let newPrizeList = [];
                    newPrizeList = wx.getStorageSync('prizeList');
                    newPrizeList[index].status = '8'; //更新为领取成功
                    wx.setStorageSync('prizeList', newPrizeList)
                    that.setData({
                        prizeList: newPrizeList,
                        isShowEntityPopup: false
                    })
                }, 1000)
            } else if (res.data.retCode == "10052") {
                setTimeout(function () {
                    wx.showToast({
                        title: '收货信息不支持表情等特殊字符，请修改后再提交哦~',
                        icon: 'none',
                        duration: 3000
                    })
                }, 100)
            } else {
                wx.redirectTo({
                    url: '../prompt/prompt?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                })
            }
        },
        fail: function (res) {
            that.isLoading(false);
            wx.redirectTo({
                url: '../prompt/prompt?retCode=' + apiCode.DRAWFAIL.code + '&retMsg=' + apiCode.DRAWFAIL.msg,
            })
        }
    });
}
/**
 * 修改中奖列表按钮上的小手显示隐藏
 */
const setHandFlag = (that) => {
    //handFlag 1未显示 2正在显示 3显示结束
    for (let item of that.data.prizeList) { //找到当前卷信息flag设置成3
        //后续有不需要显示小手但是有价值的需要优先弹窗显示的奖励继续增加prizeTypeId不等于的条件
        //世界杯卷不显示小手
        if (item.id == that.data.handPrizeId && item.prizeTypeId != 14) {
            item.handFlag = 3;
            break;
        }
    }
    for (let item of that.data.prizeList) { //找到下张有价值的卷flag设置为2显示小手
        //后续有不需要显示小手但是有价值的需要优先弹窗显示的奖励继续增加prizeTypeId不等于的条件
        //世界杯卷不显示小手
        if (item.prizeShowAmount != null && item.prizeShowAmount != "" && item.handFlag != 3 && item.prizeTypeId != 14) {
            item.handFlag = 2;
            break;
        }
    }
    wx.setStorageSync('prizeList', that.data.prizeList)
    that.setData({
        prizeList: that.data.prizeList
    })
}
/**
 * 领取权益卡奖品
 */
const receiveBenefitCard = (that, netWork, addressInfo, prizeOrderId) => {
    that.isLoading(true, "正在提交...");
    //兑奖
    netWork.POST_Json('useCustomerPrizeSubjoin', {
        data: {
            userId: wx.getStorageSync('userId'),
            prizeOrderId: prizeOrderId,
            receiveName: that.data.formValue.userName, //收货人
            receivePhone: that.data.formValue.phone, //收货电话
            receiveProvinceId: addressInfo.receiveProvinceId, //省
            receiveCityId: addressInfo.receiveCityId, //市
            receivceDistrictId: addressInfo.receivceDistrictId, //区
            receiveProvinceName: addressInfo.receiveProvinceName,
            receiveCityName: addressInfo.receiveCityName,
            receiveDistrictName: addressInfo.receiveDistrictName,
            receiveAddress: that.data.formValue.detailAddress //地址
        },
        success: function (res) {
            that.isLoading(false);
            if (res.data.retCode == undefined) {
                wx.redirectTo({
                    url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                })
            }
            if (res.data.retCode == "0000") {
                that.setData({
                    isShowEntityTips: true,
                    isShowEntityPopup: false
                })
                setTimeout(function () {
                    //权益卡详情页返回到中奖记录后领取了奖品需要把状态改成8已领取
                    if(that.data.entryMode == 'prizeRecord' || that.data.entryMode == 'remind'){
                        that.data.data.status = '8';
                        that.setData({
                            data: that.data.data
                        })
                        if(that.data.entryMode == 'prizeRecord'){
                            let pages = getCurrentPages(); //当前页面
                            let prevPage = pages[pages.length - 2]; //上一页面
                            prevPage.data.prizeList[that.data.entryModeDataIndex].status = '8'; //更新为领取成功
                            prevPage.setData({
                                prizeList: prevPage.data.prizeList,
                            })
                        }
                    }else{//else的都是中奖页进度条点击的领取实物，需要修改进度条上按钮的状态
                        that.selectComponent('#benefitCardSpeed').setReceivedSuccess();
                    }
                }, 1000)
            } else if (res.data.retCode == "10052") {
                setTimeout(function () {
                    wx.showToast({
                        title: '收货信息不支持表情等特殊字符，请修改后再提交哦~',
                        icon: 'none',
                        duration: 3000
                    })
                }, 100)
            } else {
                let productType = wx.getStorageSync('productType');
                let error_url = productType == 4 ? '/pages/xinyouranPage/prompt/prompt' : productType == 1 ? '/pages/jingdianPage/prompt/prompt' : productType == 2 ? '/pages/prompt/prompt' : productType == 3 ? '/pages/ruiPage/prompt/prompt' : '/pages/xinyouranPage/xinyouranHighPage/prompt/prompt';
                wx.redirectTo({
                    url: error_url +'?retCode='+res.data.retCode + '&retMsg=' + res.data.retMsg,
                })
            }
        },
        fail: function (res) {
            that.isLoading(false);
            wx.redirectTo({
                url: '../prompt/prompt?retCode=' + apiCode.DRAWFAIL.code + '&retMsg=' + apiCode.DRAWFAIL.msg,
            })
        }
    });
}
module.exports = {
    receivePrizeHand,
    isShowTypePope,
    revicePrize,
    setMaterialInfoAndIsHand,
    setHandFlag,
    receiveBenefitCard
};